package com.sto.stoapp.activity.center;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.StoBillFiterActivity;
import com.sto.stoapp.activity.StoLoginActivity;
import com.sto.stoapp.activity.administrator.system.AdminSystemSettingActivity;
import com.sto.stoapp.activity.sales.SalesProblemPieceSelectActivity;
import com.sto.stoapp.activity.sales.SalesTelphoneSmsActivity;
import com.sto.stoapp.activity.sales.SalesWdcpQueryActivity;
import com.sto.stoapp.activity.scanner.StoBusinessSetupActivity;
import com.sto.stoapp.activity.scanner.StoDeleteWrongScanningActivity;
import com.sto.stoapp.activity.scanner.StoRecordscheckActivity;
import com.sto.stoapp.activity.scanner.StoScanBagAndSendPieceActivity;
import com.sto.stoapp.activity.scanner.StoScanCarOperatActivity;
import com.sto.stoapp.activity.scanner.StoScanStayWarehourseActivity;
import com.sto.stoapp.activity.scanner.StoUploadMainActivity;
import com.sto.stoapp.adapter.SoleMainAdapter;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.entity.FunctionEntity;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.AlarmClockManager;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.service.TimingService;
import com.sto.stoapp.upload.UploadDataService;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHomeActivity;

import java.util.ArrayList;
import java.util.List;

import sto.android.app.StoPdaKeyEvent;


/**
 * 中转首界面
 * 
 * @author mgf
 * 
 */
public class StoCenterMainActivity extends StoHomeActivity {
	private GridView transferMainList;

	private SoleMainAdapter soleAdapter;

	// 按键映射
	private static final int[] MAPP_TO_KEY = { R.string.record_upload,
			R.string.to_piece, R.string.send_piece, R.string.problem_piece,
			R.string.package_send_piece, R.string.keep_ware_piece,
			R.string.vehicle_operation, R.string.super_limits_search,
			R.string.del_error_code, R.string.record_search };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// ExceptionLog.writeLog("center login", "init StoCenterMainActivity");
		setContentView(R.layout.sto_center_main);
		this.setStoTitle(R.string.center_title);
		// ExceptionLog.writeLog("center login",
		// "init StoCenterMainActivity initWidget");
		initWidget();
		// 登入类型,用于后面业务判断是业务员或扫描员类型
		// UnifiedStaticType.loginType = BaseMessage.CENTER_VERSION;
		// UnSentDataManager.getInstance().setUnSent(UploadDataManager.getInstance(this).getUnsendDataCount());
		initUnsentDataCount();
		ExceptionLog.writeLog("center login",
				"init StoCenterMainActivity finish");
	}

	private void initWidget() {
		transferMainList = (GridView) findViewById(R.id.transfer_main_list);
		soleAdapter = new SoleMainAdapter(this, getResourceList());
		transferMainList.setAdapter(soleAdapter);
		transferMainList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				arg1.setSelected(true);
				TextView title = (TextView) arg1.findViewById(R.id.res_test);
				clickItemEvent(title.getText().toString());
			}
		});

	}

	private void clickItemEvent(String title) {
		// 中转-到件
		if (title.equals(getText(R.string.to_piece))) {
			// if(checkTimeSyn()){
			// Intent intent = new Intent(this, StoScanToPieceActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			// }
			checkTimeSyn(StoCenterToPieceActivity.class, this, "");
		}
		// 中转-发件
		else if (title.equals(getText(R.string.send_piece))) {
			// if(checkTimeSyn()){
			// Intent intent = new Intent(this, StoScanSendPieceActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			// }
			checkTimeSyn(StoCenterSendPieceActivity.class, this, "");
		}
		// 中转-问题件
		else if (title.equals(getText(R.string.problem_piece))) {
			// if(checkTimeSyn()){
			// Intent intent = new Intent(this,
			// SalesProblemPieceActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			// }
			checkTimeSyn(SalesProblemPieceSelectActivity.class, this,
					HomeBroadAction.CENTER_BROAD);
		}
		// 中转-装袋&发件
		else if (title.equals(getText(R.string.package_send_piece))) {
			// if(checkTimeSyn()){
			// Intent intent = new Intent(this,
			// StoScanBagAndSendPieceActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			// }
			checkTimeSyn(StoScanBagAndSendPieceActivity.class, this,
					HomeBroadAction.CENTER_BROAD);
		}
		// 中转-留仓件
		else if (title.equals(getText(R.string.stay_warehourse_piece))) {
			// if(checkTimeSyn()){
			// Intent intent = new Intent(this,
			// StoScanStayWarehourseActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			// }
			checkTimeSyn(StoScanStayWarehourseActivity.class, this,
					HomeBroadAction.CENTER_BROAD);
		}
		// 中转-车辆操作
		else if (title.equals(getText(R.string.vehicle_operation))) {
			Intent intent = new Intent(this, StoScanCarOperatActivity.class);
			intent.putExtra("busiType", HomeBroadAction.CENTER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 中转-无点超派
		else if (title.equals(getText(R.string.super_limits_search))) {
			Intent intent = new Intent(this, SalesWdcpQueryActivity.class);
			intent.putExtra("busiType", HomeBroadAction.CENTER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 中转-删除错扫
		else if (title.equals(getText(R.string.del_error_code))) {
			Intent intent = new Intent(this,
					StoDeleteWrongScanningActivity.class);
			intent.putExtra("busiType", HomeBroadAction.CENTER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 中转-记录查询
		else if (title.equals(getText(R.string.record_search))) {
			Intent intent = new Intent(this, StoRecordscheckActivity.class);
			intent.putExtra("busiType", HomeBroadAction.CENTER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 中转-记录上传
		else if (title.equals(getText(R.string.record_upload))) {
			Intent intent = new Intent(this, StoUploadMainActivity.class);
			intent.putExtra("busiType", HomeBroadAction.CENTER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 中转-业务设置
		else if (title.equals(getText(R.string.business_settings))) {
			Intent intent = new Intent(this, StoBusinessSetupActivity.class);
			intent.putExtra("busiType", HomeBroadAction.CENTER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 中转-电话短信
		else if (title.equals(getText(R.string.telphone_sms))) {
			Intent intent = new Intent(this, SalesTelphoneSmsActivity.class);
			intent.putExtra("busiType", HomeBroadAction.CENTER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 中转-系统设置
		else if (title.equals(getText(R.string.system_settings))) {
			Intent intent = new Intent(this, AdminSystemSettingActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra(HomeBroadAction.BROAD_TYPE,
					HomeBroadAction.CENTER_BROAD);
			startActivity(intent);
		}
		else if(title.equals(getText(R.string.filter))){
			Intent intent =new Intent(this, StoBillFiterActivity.class);
			intent.putExtra("busiType", HomeBroadAction.CENTER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 中转-用户切换
		else {
			onBackPressed();
		}
	}

	/**
	 * 时间同步检测
	 * 
	 * @param c
	 * @param type
	 */
	private void checkTimeSyn(final Class<?> c, final Context context,
			final String type) {
		if (!(StoFilePreference.getInstance(StoCenterMainActivity.this)
				.getsetTimeSynch())) {
			final BaseDialog dialog = new BaseDialog(this);
			dialog.setTitles(getString(R.string.synch_time_hint));
			dialog.show();
			dialog.setOnBackClickListener(new OnBackClickListener() {
				@Override
				public void onBackClickListener(boolean res) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					if (res) {
						Intent intent = new Intent(context, c);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intent.putExtra("busiType", type);
						startActivity(intent);
					}
				}
			});
		} else {
			Intent intent = new Intent(context, c);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("busiType", type);
			this.startActivity(intent);
		}
	}

	private List<FunctionEntity> getResourceList() {
		List<String> resList = new ArrayList<String>();
		int[] picIds = { R.drawable.arrived_piece, R.drawable.send_piece,
				R.drawable.problem_piece, R.drawable.package_send_piece,
				R.drawable.keep_ware_piece, R.drawable.vehicle_operation,
				R.drawable.super_limits_search, R.drawable.del_error_code,
				R.drawable.record_search, R.drawable.record_upload,
				R.drawable.business_settings, R.drawable.kai_after_sales,
				R.drawable.telphone_sms, R.drawable.bill_filter,
				R.drawable.system_settings, R.drawable.logout };
		resList.add(getText(R.string.arrived_piece).toString());
		resList.add(getText(R.string.send_piece).toString());
		resList.add(getText(R.string.problem_piece).toString());
		resList.add(getText(R.string.package_send_piece).toString());
		resList.add(getText(R.string.keep_ware_piece).toString());
		resList.add(getText(R.string.vehicle_operation).toString());
		resList.add(getText(R.string.super_limits_search).toString());
		resList.add(getText(R.string.del_error_code).toString());
		resList.add(getText(R.string.record_search).toString());
		resList.add(getText(R.string.record_upload).toString());
		resList.add(getText(R.string.business_settings).toString());
		resList.add(getText(R.string.telphone_sms).toString());
		resList.add(getText(R.string.system_settings).toString());
		resList.add(getText(R.string.filter).toString());
		resList.add(getText(R.string.logout).toString());
		List<FunctionEntity> functionList = new ArrayList<FunctionEntity>();
		for (int i = 0; i < resList.size(); i++) {
			FunctionEntity entity = new FunctionEntity();
			entity.setTitle(resList.get(i));
			entity.setPicId(picIds[i]);
			functionList.add(entity);
		}
		return functionList;
	}

	@Override
	public void onBackPressed() {
		Helper.logoutAlert(this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		// 退出
		if (intent.getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE) != null) {
			if ((Intent.FLAG_ACTIVITY_CLEAR_TOP & intent.getFlags()) != 0
					&& intent
							.getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE)
							.equals(HomeBroadAction.ALARM_LOGOUT)) {
				// StoFilePreference.getInstance(this).clearLoginInfo();
				// StoFilePreference.getInstance(this).clearOderAndTimeSynData();
				Intent logoutIntent = new Intent(this, StoLoginActivity.class);
				startActivity(logoutIntent);
//				new LogoutThread(StoCenterMainActivity.this, null, false)
//						.start();
				finish();
			}
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		System.out.println("onDestroy sales");
		if (!UnifiedStaticType.NOT_CLOSE) {
			stopService(new Intent(this, StoDownServer.class));
			StoFilePreference.getInstance(StoCenterMainActivity.this)
					.clearOderAndTimeSynData();
			stopService(new Intent(this, UploadDataService.class));
			stopService(new Intent(this, TimingService.class));
		}
		UnifiedStaticType.NOT_CLOSE = false;
		super.onDestroy();
	}

//	/**
//	 * 按键映射 数字键0~9映射（0表示列表第十条数据）
//	 */
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) {
//			clickItemEvent(getString(MAPP_TO_KEY[keyCode - KeyEvent.KEYCODE_0]));
//		}
//		return super.onKeyDown(keyCode, event);
//	}

	/**
	 * 小退 返回中心选择状态
	 */
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// if (AccessControlManager.getInstance(this).getJobSelect()) {
		if (keyCode == StoPdaKeyEvent.KEYCODE_DEL) {
			startActivity(new Intent(this, StoCenterSelectActivity.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
			this.finish();
		}
		// }
		return super.onKeyUp(keyCode, event);
	}
}
